<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Offer extends SMB_Controller {
	
	public function __construct() {
		parent::__construct();
		$this->load->library('scholarship');
	}
	
	public function index() {
		$this->_get_userinfo();
		
		$this->load->helper('ext_form');
		$this->load->helper('table');
		
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
		$params = array(
			'role' => $this->userinfo['role'],
			'addstatus' => $this->session->flashdata('addstatus'),
			'editstatus' => $this->session->flashdata('editstatus'),
			'sponsors' => $this->scholarship->get_sponsor()
		);
		
		if ($this->input->get('search') == FALSE) {
			$limit = $this->scholarship->count_all_scholarship(PENDAFTARAN);
			$params['scholarships'] = $this->scholarship->list_offered_scholarship('0', $limit, PENDAFTARAN);
			$params['title'] = 'Daftar Beasiswa Ditawarkan';
			$params['empty'] = 'Tidak ada beasiswa ditawarkan.';
		} else {
			$name = $this->input->get('name', TRUE);
			$sponsor = $this->input->get('sponsor', TRUE);
			if ($name == FALSE) { $name = ''; }
			if ($sponsor == FALSE) { $sponsor = ''; }
			$limit = $this->scholarship->count_all_scholarship(PENDAFTARAN, $name, $sponsor);
			$params['title'] = 'Daftar Hasil Pencarian Beasiswa';
			$params['empty'] = 'Tidak ada beasiswa ditawarkan sesuai dengan kriteria pencarian.';
			$params['scholarships'] = $this->scholarship->list_offered_scholarship('0', $limit, PENDAFTARAN, $name, $sponsor);
		}
		
		$params['pager'] = get_pager(6);
		$this->load->view('common/scholar_offer_list', $params); 
		$this->_load_common_footer();
	}
	
	public function detail($id = NULL, $offset = '0') {
		$this->_get_userinfo();
		if ($id == NULL) {
			redirect($this->userinfo['role'].'/scholar/offer/index', 'location');
			exit;
		}
		$scholarship = $this->scholarship->get_scholarship_by_id_and_status($id, PENDAFTARAN);
		if ($scholarship == NULL) {
			redirect($this->userinfo['role'].'/scholar/offer/index', 'location');
			exit;
		}
		
		$this->load->helper('table');
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
		$params = array(
			'role' => $this->userinfo['role'],
			'scholarship' => $scholarship,
			'type' => PENDAFTARAN,
			'status' => 'masa pendaftaran',
			'counter' => $this->scholarship->count_reciever_scholarship($scholarship->id, PENDAFTARAN),
			'verified' => $this->scholarship->count_reciever_scholarship($scholarship->id, TERVERIFIKASI),
			'invited' => $this->scholarship->count_reciever_scholarship($scholarship->id, PRIVAT),
			'studentstatus' => 'Status Pendaftaran',
			'countertitle' => 'Jumlah Pendaftar',
			'pager1' => get_pager(4, 'pager1'),
			'pager2' => get_pager(4, 'pager2'),
			'pager3' => get_pager(3, 'pager3') 
		);
		$params['recievers'] = $this->scholarship->get_reciever_scholarship($id, '0', $params['counter'], PENDAFTARAN);
		$params['recieversverified'] = $this->scholarship->get_reciever_scholarship($id, '0', $params['verified'], TERVERIFIKASI);
		$params['recieversinvited'] = $this->scholarship->get_reciever_scholarship($id, '0', $params['invited'], PRIVAT);
		$this->load->view('common/scholar_offer_detail', $params);
		$this->_load_common_footer();
	}
	
	public function add() {
		$this->_get_userinfo();
		$this->load->library('file');
		
		$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
		$validatefiles = $this->_validate_file($this->input->post('addfiles'));
		if ($this->form_validation->run('add_scholarship') == FALSE 
				|| $validatefiles != '') {
			$this->_load_common_header();
			$this->_load_common_navigation();
			$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
			$params = array(
				'role' => $this->userinfo['role'],
				'types' => unserialize(SCHOLARSHIP_TYPE),
				'files' => $this->file->get_categories(),
				'sponsors' => $this->scholarship->get_sponsor(),
				'addfiles' => $this->input->post('addfiles'),
				'validatefiles' => $validatefiles
			);
			$this->load->view('common/scholar_offer_add', $params); 
			$this->_load_common_footer();
		} else {
			$scholar = array(
				'name' => $this->input->post('name', TRUE),
				'periodstart' => $this->input->post('periodstart', TRUE),
				'periodend' => $this->input->post('periodend', TRUE),
				'deadline' => $this->input->post('deadline', TRUE),
				'type' => $this->input->post('type', TRUE),
				'sponsor_id' => $this->input->post('sponsor_id', TRUE),
				'requiredfiles' => $this->input->post('requiredfiles'),
				'addfiles' => $this->input->post('addfiles'),
				'details' => $this->input->post('details'),
			);
			$result = $this->scholarship->add_scholarship($scholar);
			if ($result == FALSE) {
				$this->session->set_flashdata('addstatus', 'failed');
				redirect('adkesma/scholar/offer/index', 'refresh');
			} else {
				$id = $this->scholarship->get_scholarship_id($scholar['sponsor_id'],
						$scholar['name'], $scholar['periodstart'], $scholar['periodend']);
				$this->session->set_flashdata('addstatus', 'success');
				if ($scholar['type'] == 'privat') {
					redirect('adkesma/scholar/offer/invite/'.$id, 'refresh');
				} else {
					redirect('adkesma/scholar/offer/index', 'refresh');
				}
			}
		}
	}
	
	public function edit($id = NULL) {
		$this->_get_userinfo();
		if ($id == NULL) {
			redirect($this->userinfo['role'].'/scholar/offer/index', 'location');
			exit;
		}
		$scholarship = $this->scholarship->get_scholarship_by_id_and_status($id, PENDAFTARAN);
		if ($scholarship == NULL) {
			$scholarship = $this->scholarship->get_scholarship_by_id_and_status($id, SELEKSI);
		}
		if ($scholarship == NULL) {
			redirect($this->userinfo['role'].'/scholar/offer/index', 'location');
			exit;
		}
		$this->load->library('file');
		$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
		$validatefiles = $this->_validate_file($this->input->post('addfiles'));
		$validatefiles = $this->_validate_file($this->input->post('addfiles'));
		if ($this->form_validation->run('add_scholarship') == FALSE 
				|| $validatefiles != '') {
			$this->_load_common_header();
			$this->_load_common_navigation();
			$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
			$reqfiles = array();
			$reqfilesobj = $this->scholarship->get_required_file($id);
			if ($reqfilesobj != NULL) {
				foreach ($reqfilesobj as $file) {
					$reqfiles[] = $file->id;
				}
			}
			$params = array(
				'scholarship' => $scholarship,
				'role' => $this->userinfo['role'],
				'types' => unserialize(SCHOLARSHIP_TYPE),
				'files' => $this->file->get_categories(),
				'sponsors' => $this->scholarship->get_sponsor(),
				'addfiles' => $this->input->post('addfiles'),
				'validatefiles' => $validatefiles,
				'requiredfiles' => $reqfiles
			);
			$this->load->view('common/scholar_offer_edit', $params); 
			$this->_load_common_footer();
		} else {
			$scholar = array(
				'name' => $this->input->post('name', TRUE),
				'periodstart' => $this->input->post('periodstart', TRUE),
				'periodend' => $this->input->post('periodend', TRUE),
				'deadline' => $this->input->post('deadline', TRUE),
				'type' => $this->input->post('type', TRUE),
				'sponsor_id' => $this->input->post('sponsor_id', TRUE),
				'requiredfiles' => $this->input->post('requiredfiles'),
				'addfiles' => $this->input->post('addfiles'),
				'details' => $this->input->post('details'),
			);
			$result = $this->scholarship->edit_scholarship($id, $scholar);
			if ($result == FALSE) {
				$this->session->set_flashdata('editstatus', 'failed');
				redirect('adkesma/scholar/offer/index', 'refresh');
			} else {
				$this->session->set_flashdata('editstatus', 'success');
				if ($scholar['type'] == 'privat') {
					redirect('adkesma/scholar/offer/invite/'.$id, 'refresh');
				} else {
					redirect('adkesma/scholar/offer/index', 'refresh');
				}
			}
		}
	}
	
	public function saveverify() {
		if ($this->input->is_ajax_request()) {
			$checked = $this->input->post('checked');
			$id = $this->input->post('id');
			$name = $this->input->post('name');
			if ($checked != FALSE && $id != FALSE && $name != FALSE) {
				$name = explode('@', $name);
				if ($checked == 'false') {
					$checked = 'mendaftar';
					$result = $this->scholarship->update_status_applicant($id, $name[0], $checked);
					if ($result == TRUE) {
						$output = array(
							'type' => 'warning',
							'status' => 'success',
						);
						$output['message'] = 'Status verifikasi '.$name[1].' dibatalkan.';
						$this->output->set_header('Content-Type: application/json; charset=utf-8');
						echo json_encode($output);
						exit;
					} else {
						
					}
				} else if ($checked == 'true') {
					$checked = 'terverifikasi';
					$result = $this->scholarship->update_status_applicant($id, $name[0], $checked);
					if ($result == TRUE) {
						$output = array(
							'type' => 'warning',
							'status' => 'success',
						);
						$output['message'] = 'Mahasiswa '.$name[1].' berhasil diverifikasi.';
						$this->output->set_header('Content-Type: application/json; charset=utf-8');
						echo json_encode($output);
						exit;
					}
				}
			}
			$output = array(
				'type' => 'error',
				'status' => 'failed',
			);
			$output['message'] = 'Gagal ubah status. Silakan coba beberapa saat lagi.';
			$this->output->set_header('Content-Type: application/json; charset=utf-8');
			echo json_encode($output);
			exit;
		} else {
			$this->output->set_status_header('405');
			show_error("The method you requested is not allowed.", 405, "405 Method Not Allowed");
		}
	}
	
	public function saveinvite() {
		if ($this->input->is_ajax_request()) {
			$checked = $this->input->post('checked');
			$id = $this->input->post('id');
			$name = $this->input->post('name');
			if ($checked != FALSE && $id != FALSE && $name != FALSE) {
				$name = explode('@', $name);
				if ($checked == 'false') {
					$result = $this->scholarship->update_status_applicant($id, $name[0], $checked, TRUE);
					if ($result == TRUE) {
						$output = array(
							'type' => 'warning',
							'status' => 'success',
						);
						$output['message'] = 'Status undangan '.$name[1].' dibatalkan.';
						$this->output->set_header('Content-Type: application/json; charset=utf-8');
						echo json_encode($output);
						exit;
					}
				} else if ($checked == 'true') {
					$checked = 'ditawarkan';
					$result = $this->scholarship->update_status_applicant($id, $name[0], $checked);
					if ($result == TRUE) {
						$output = array(
							'type' => 'warning',
							'status' => 'success',
						);
						$output['message'] = 'Mahasiswa '.$name[1].' berhasil diundang.';
						$this->output->set_header('Content-Type: application/json; charset=utf-8');
						echo json_encode($output);
						exit;
					}
				} 
			}
			$output = array(
				'type' => 'error',
				'status' => 'failed',
			);
			$output['message'] = 'Gagal ubah status. Silakan coba beberapa saat lagi.';
			$this->output->set_header('Content-Type: application/json; charset=utf-8');
			echo json_encode($output);
			exit;
		} else {
			$this->output->set_status_header('405');
			show_error("The method you requested is not allowed.", 405, "405 Method Not Allowed");
		}
	}
	
	public function verify($id = NULL) {
		$this->_get_userinfo();
		if ($id == NULL) {
			redirect('adkesma/scholar/offer/index', 'location');
			exit;
		}
		$scholarship = $this->scholarship->get_scholarship_by_id_and_status($id, PENDAFTARAN);
		if ($scholarship == NULL) {
			redirect('adkesma/scholar/offer/index', 'location');
			exit;
		}
		$this->load->helper('table');
		$this->load->helper('ext_form');
		$this->load->library('data');
		
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
		$params = array(
			'scholarship' => $scholarship,
			'role' => $this->userinfo['role'],
			'years' => $this->data->list_year(),
			'majors' => $this->data->list_major()		
		);
		
		if ($this->input->get('search') == FALSE) {
			$limit = $this->scholarship->count_verify_student($id);
			$params['students'] = $this->scholarship->search_verify_student($id, '0', $limit);
			$params['title'] = 'Daftar Semua Mahasiswa';
			$params['empty'] = 'Tidak ditemukan mahasiswa.';
		} else {
			$name = $this->input->get('name', TRUE);
			$year = $this->input->get('year', TRUE);
			$major = $this->input->get('major', TRUE);
			if ($name == FALSE) { $name = ''; }
			if ($year == FALSE) { $year = ''; }
			if ($major == FALSE) { $major = ''; }
			$limit = $this->scholarship->count_verify_student($id, $name, $year, $major);
			$params['empty'] = 'Tidak ditemukan mahasiswa yang sesuai dengan kriteria pencarian.';
			$params['title'] = 'Daftar Hasil Pencarian Mahasiswa';
			$params['students'] = $this->scholarship->search_verify_student($id, '0', $limit, $name, $year, $major);
		}
		
		$params['pager'] = get_pager(4);
		$this->load->view('common/scholar_offer_verify', $params);
		$this->_load_common_footer();
	}
	
	public function invite($id = NULL) {
		$this->_get_userinfo();
		if ($id == NULL) { 
			redirect('adkesma/scholar/offer/index', 'location');
			exit;
		}
		$scholarship = $this->scholarship->get_scholarship_by_id_and_status($id, PENDAFTARAN);
		if ($scholarship == NULL || ($scholarship != NULL && $scholarship->type != 'privat')) {
			redirect('adkesma/scholar/offer/index', 'location');
			exit;
		}
		$this->load->helper('table');		
		$this->load->helper('ext_form');
		$this->load->library('data');
		
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
		$params = array(
			'scholarship' => $scholarship,
			'role' => $this->userinfo['role'],
			'years' => $this->data->list_year(),
			'majors' => $this->data->list_major()
		);
		
		if ($this->input->get('search') == FALSE) {
			$limit = $this->scholarship->count_invite_student($id);
			$params['students'] = $this->scholarship->search_invite_student($id, '0', $limit);
			$params['title'] = 'Daftar Semua Mahasiswa';
			$params['empty'] = 'Tidak ditemukan mahasiswa.';
			$params['gpavalid'] = $this->session->flashdata('gpavalid');
		} else {
			$gpavalid = $this->_validate_gpa($this->input->get('gpa', TRUE));
			if ($gpavalid != '') {
				$this->session->set_flashdata('gpavalid', $gpavalid);
				unset($_GET['search']);
				redirect($this->userinfo['role'].'/scholar/offer/invite/'.$id.'?'.http_build_query($_GET, '', '&'), 'location');
				exit;
			}
			$name = $this->input->get('name', TRUE);
			$year = $this->input->get('year', TRUE);
			$major = $this->input->get('major', TRUE);
			$gpa = $this->input->get('gpa', TRUE);
			if ($name == FALSE) { $name = ''; }
			if ($year == FALSE) { $year = ''; }
			if ($major == FALSE) { $major = ''; }
			if ($gpa == FALSE) { $gpa = 0.00; } else { $gpa = doubleval($gpa); }
			$limit = $this->scholarship->count_invite_student($id, $name, $year, $major, $gpa);
			$params['empty'] = 'Tidak ditemukan mahasiswa yang sesuai dengan kriteria pencarian.';
			$params['title'] = 'Daftar Hasil Pencarian Mahasiswa';
			$params['students'] = $this->scholarship->search_invite_student($id, '0', $limit, $name, $year, $major, $gpa);
		}
		
		$params['pager'] = get_pager(5);
		$this->load->view('common/scholar_offer_invite', $params);
		$this->_load_common_footer();
	}
	
	private function _validate_gpa($str) {
		if ($str == FALSE) {
			return '';
		} else if (preg_match('/^[0-9]{1}(\.[0-9]{1,2}){0,1}$/', $str) == 1) {
			$gpa = doubleval($str);
			if ($gpa < 0 || $gpa > 4) {
				return '<span class="error">Range IPK dari 0.00 - 4.00</span>';
			} else { 
				return '';
			}
		} else {
			return '<span class="error">Format IPK salah. Format yang benar: #.##</span>';
		}
	}
	
	public function _validate_period_start($str) {
		if ($this->_validate_date($str)) {
			return TRUE;	
		} else {
			$this->form_validation->set_message('_validate_period_start', 'Format tanggal tidak valid. Format tanggal yang benar yyyy-mm-dd');
			return FALSE;
		}
	}
	
	public function _validate_period_end($str) {
		if ($this->_validate_date($str)) {
			$check = $this->_validate_date($this->input->post('periodstart'));
			if ($check == FALSE) {
				$this->form_validation->set_message('_validate_period_end', '');
				return FALSE;
			} 
			$start = strtotime($this->input->post('periodstart'));
			$end = strtotime($str);
			if ($start >= $end) {
				$this->form_validation->set_message('_validate_period_end', 'Akhir Periode harus lebih dari Awal Periode');
				return FALSE;
			} else {
				return TRUE;
			}	
		} else {
			$this->form_validation->set_message('_validate_period_end', 'Format tanggal tidak valid. Format tanggal yang benar yyyy-mm-dd');
			return FALSE;
		}
	}
	
	public function _validate_deadline($str) {
		if ($this->_validate_date($str)) {
			$check = $this->_validate_date($this->input->post('periodstart'));
			if ($check == FALSE) {
				$this->form_validation->set_message('_validate_deadline', '');
				return FALSE;
			} 
			$start = strtotime($this->input->post('periodstart'));
			$deadline = strtotime($str);
			$today = strtotime('today');
			if ($deadline <= $today) {
				$this->form_validation->set_message('_validate_deadline', 'Batas Pendaftaran harus lebih dari hari ini');
				return FALSE;
			}
			if ($start <= $deadline) {
				$this->form_validation->set_message('_validate_deadline', 'Batas Pendaftaran harus kurang dari Awal Periode');
				return FALSE;
			} else {
				return TRUE;
			}
			return TRUE;
		} else {
			$this->form_validation->set_message('_validate_deadline', 'Format tanggal tidak valid. Format tanggal yang benar yyyy-mm-dd');
			return FALSE;
		}
	}
	
	private function _validate_file($files) {
		if ($files == FALSE) {
			return '';
		} else {
			$files = array_map('trim', $files);
			$files = array_filter($files);
			$count = count(array_unique($files)) == count($files);
			$uniq = $this->file->is_unique_files($files);
			if ($count == FALSE || $uniq == FALSE) {
				return '<span class="error">Field Berkas Tambahan harus unik</span><br />';
			} else {
				return '';
			}
		}
	}
	
	private function _validate_date($str) {
		if ($str == '') {
			return FALSE;
		}
		$date = explode("-", $str);
		return checkdate(intval($date[1]), intval($date[2]), intval($date[0]));
	}
}
